package com.xiashitech.authservice.util;

import com.tencent.bk.sdk.iam.dto.InstanceDTO;
import com.tencent.bk.sdk.iam.dto.PathInfoDTO;
import com.tencent.bk.sdk.iam.util.PathBuilder;
import com.xiashitech.authservice.config.AuthHelperCache;
import com.xiashitech.authservice.constants.ResourceTypeEnum;
import com.xiashitech.authservice.constants.ResourceTypeId;
import com.xiashitech.interfaces.authservice.dto.AuthDTO;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class IamAuthUtil {

    public static InstanceDTO buildInstance(String resourceType, String resourceId, String systemId, PathInfoDTO path) {
        InstanceDTO instance = new InstanceDTO();
        instance.setSystem(systemId);
        instance.setId(resourceId);
        instance.setType(resourceType);
        instance.setPath(path);
        if(resourceType.endsWith(ResourceTypeEnum.COLUMN.getId())) {
            Map<String,Object> attribute = new HashMap<String,Object>();
            attribute.put("_bk_iam_path_","/"+resourceType.substring(0,resourceType.lastIndexOf("-"+ResourceTypeEnum.COLUMN.getId()))+","+resourceId.substring(0,resourceId.lastIndexOf("."))+"/");
            instance.setAttribute(attribute);
        }
        return instance;
    }

    public static PathInfoDTO buildTablePathInfoDTO(String databaseService,String databaseName,String databaseSchema,String tableName) {
        return buildColumnPathInfoDTO(databaseService,databaseName,databaseSchema,tableName,null);
    }

    public static PathInfoDTO buildColumnPathInfoDTO(String databaseService,String databaseName,String databaseSchema,String tableName,String columnName) {
        String database = String.format("%s.%s", databaseService, databaseName);
        String schema = String.format("%s.%s", database, databaseSchema);
        String table = String.format("%s.%s", schema, tableName);
        String column = null;
        if(columnName != null) {
            column = String.format("%s.%s", table, columnName);
        }

        PathBuilder pathBuilder = PathBuilder.newBuilder(
                        ResourceTypeId.DATABASE_SERVICE, databaseService)
                .child(
                        ResourceTypeId.DATABASE, database)
                .child(
                        ResourceTypeId.DATABASE_SCHEMA, schema
                ).child(
                        ResourceTypeId.TABLE, table
                );
        if(column != null) {
            pathBuilder.child(ResourceTypeId.COLUMN, column);
        }
        return pathBuilder.build();
    }
}
